<template>
  <div class="InstitutionManage-wrapper">
    <!-- 左侧树形结构 -->
    <div class="left-content">
     <h2>岗位管理</h2>
      <div>
       <a-input-search style="margin-bottom: 8px" placeholder="请输入关键字" @change="onChange" class="leftSearchInput" />
       <a-tree
         :auto-expand-parent="true"
         :tree-data="realgData"
         :replaceFields = "{children:'child', title:'name', key:'id'}"
         @select="chooseTreeNode"
       >
         <template slot="title" slot-scope="{ title }">
           <span v-if="title.indexOf(searchValue) > -1">
             {{ title.substr(0, title.indexOf(searchValue)) }}
             <span style="color: #f50">{{ searchValue }}</span>
             {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
           </span>
           <span v-else>{{ title }}</span>
         </template>
       </a-tree>
     </div>
    </div>
    <!-- 右侧展示结构 -->
    <div class="right-content">
      <!-- 头部搜索区域 -->
      <div class="search-wrapper">
        <!-- 头部搜索 -->
        <a-form-model :model="searchFormData" :label-col="labelCol" :wrapper-col="wrapperCol" ref="searchFormRef">
           <a-form-model-item label="组织名称:" class="serach-input">
             <a-input placeholder = "模糊搜索组织名称" size = "large" v-model="searchFormData.name"/>
           </a-form-model-item>
        </a-form-model>
        <!-- 按钮组 -->
        <div class="btn-group">
          <a-button type="success" icon="search" @click="searchBtnClick" style="background-color:#0079FE;color:#fff">
           查询
         </a-button>
         <a-button @click="resetBtnClick">重置</a-button>
        </div>
      </div>
      <!-- 底部新增按钮和表格 -->
      <div class="table-area">
        <a-button type="primary" icon="plus" class="plus-btn" @click="addBtn" style="background-color:#0079FE;color:#fff">新增</a-button>
        <!-- <button  class="plus-btn" @click="addBtn">新增11</button> -->
        <!-- 表格 -->
        <a-table :columns="columns" :data-source="tableData" rowKey = "id">
           <!-- <a slot="name" slot-scope="text">{{ text }}</a>
           <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
           <span slot="tags" slot-scope="tags">
             <a-tag
               v-for="tag in tags"
               :key="tag"
               :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
             >
               {{ tag.toUpperCase() }}
             </a-tag>
           </span> -->
           <span slot="action" slot-scope="text">
           <!-- <span slot="action"> -->
             <a @click="editItem(text)">编辑</a>
             <a-divider type="vertical" />
             <a @click="disabledItem(text)">{{text.shield == 0? "禁用":"启用"}}</a>
             <a-divider type="vertical" />
             <a-popconfirm
                :title="text.actualUserNumber == 0?'确定删除这一行吗?':'到岗人数不为0,无法删除'"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirm(text)"
                @cancel="cancel"
              >
                <a href="#">删除</a>
              </a-popconfirm>
           </span>
         </a-table>
      </div>
    </div>
 
    <!-- 表格数据编辑对话框 -->
   <a-modal
       title="编辑"
       :visible="editDialogVisible"
       :confirm-loading="confirmLoading"
       @ok="editDialogHandleOk"
       @cancel="editDialogHandleCancel"
     >
     <a-form-model ref = "editFormRef"  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" :model="editDialogFormData" :rules = "editDialogFormRules">
       <a-form-model-item label="组织名称" prop = "orgName">
        <span>{{editDialogFormData.orgName}}</span>
       </a-form-model-item>
       <a-form-model-item label="岗位" prop = "name">
         <a-input placeholder = "请输入岗位名称" v-model="editDialogFormData.name"></a-input>
       </a-form-model-item>
       <a-form-model-item label="计划岗位人数" prop = "plantUserNumber">
         <a-input placeholder = "请输入计划岗位人数" v-model="editDialogFormData.plantUserNumber"></a-input>
       </a-form-model-item>
     </a-form-model>
   </a-modal>
   <!-- 新增数据对话框 -->
   <a-modal
      title="新增"
      :visible="addDialogVisible"
      :confirm-loading="confirmLoading"
      @ok="addDialogHandleOk"
      @cancel="addDialogHandleCancel"
    >
      <a-form-model ref = "addFormRef"  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" :model="addDialogFormData" :rules = "editDialogFormRules">
        <a-form-model-item label="组织名称" prop = "orgName">
          <span>{{orgName}}</span>
        </a-form-model-item>
        <a-form-model-item label="岗位" prop = "name">
          <a-input placeholder = "请输入岗位名称" v-model="addDialogFormData.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="计划岗位人数" prop = "plantUserNumber">
          <a-input placeholder = "请输入计划岗位人数" v-model="addDialogFormData.plantUserNumber"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
 </template>
 
 <script>
 // 表格数据源
 const data = [
   {
     key: '1',
     name: 'John Brown',
     age: 32,
     address: 'New York No. 1 Lake Park',
     tags: ['nice', 'developer'],
   },
   {
     key: '2',
     name: 'Jim Green',
     age: 42,
     address: 'London No. 1 Lake Park',
     tags: ['loser'],
   },
   {
     key: '3',
     name: 'Joe Black',
     age: 32,
     address: 'Sidney No. 1 Lake Park',
     tags: ['cool', 'teacher'],
   },
 ];
 // 表格头部初始化数据
 const columns = [
   {
     title: '序号',
     dataIndex: 'index',
     key: 'index',
     customRender: (text,record,index) => `${index+1}`,
   },
   {
     dataIndex: 'name',
     key: 'name',
     // slots: { title: 'customTitle' },
     // scopedSlots: { customRender: 'name' },
     title:"岗位名称"
   },
   {
     title: '部门名称',
     dataIndex: 'orgName',
     key: 'orgName',
   },
   {
     title: '实际到岗人数',
     dataIndex: 'actualUserNumber',
     key: 'actualUserNumber',
   },
   {
     title: '计划到岗人数',
     key: 'plantUserNumber',
     dataIndex: 'plantUserNumber',
   },
   {
     title: '创建时间',
     key: 'createTime',
     dataIndex: 'createTime',
   },
   {
     title: '操作',
     key: 'action',
     scopedSlots: { customRender: 'action' },
   },
 ];
 // 树形结构初始化数据
   const x = 3;
   const y = 2;
   const z = 1;
   const gData = [];
 
   const generateData = (_level, _preKey, _tns) => {
     const preKey = _preKey || '0';
     const tns = _tns || gData;
 
     const children = [];
     for (let i = 0; i < x; i++) {
       const key = `${preKey}-${i}`;
       tns.push({ title: key, key, scopedSlots: { title: 'title' } });
       if (i < y) {
         children.push(key);
       }
     }
     if (_level < 0) {
       return tns;
     }
     const level = _level - 1;
     children.forEach((key, index) => {
       tns[index].children = [];
       return generateData(level, key, tns[index].children);
     });
   };
   generateData(z);
 
   const dataList = [];
   const generateList = data => {
     for (let i = 0; i < data.length; i++) {
       const node = data[i];
       const key = node.key;
       dataList.push({ key, title: key });
       if (node.children) {
         generateList(node.children);
       }
     }
   };
   generateList(gData);
 
   const getParentKey = (key, tree) => {
     let parentKey;
     for (let i = 0; i < tree.length; i++) {
       const node = tree[i];
       if (node.children) {
         if (node.children.some(item => item.key === key)) {
           parentKey = node.key;
         } else if (getParentKey(key, node.children)) {
           parentKey = getParentKey(key, node.children);
         }
       }
     }
     return parentKey;
   };
 
   import {  InstitutionManageListData,InstitutionManageListDataDisabled,postManageTreeData,postManageListData,postManageListDataPOST,
    postManageListDataDelete} from '@/services/user.js'
  export default {
   name: '',
   data () {
    return {
       expandedKeys: [],
       searchValue: '',
       autoExpandParent: true,
       gData,
       labelCol: { span: 4 },
       wrapperCol: { span: 14 },
       data,
       columns,
       realgData:[],
       // 点击树状图节点,获取父级部门id
       orgId:"",
       //  部门名称
       orgName : "",
       // 搜索表单数据
       searchFormData:{
         name:""
       },
       // 表格数据
       tableData:[],
       // 编辑对话框显示隐藏
       editDialogVisible:false,
       // 新增对话框显示隐藏
       addDialogVisible:false,
       // 编辑对话框确认按钮状态
       // 新增对话框确认按钮状态
       confirmLoading:false,
       // 编辑对话框表格数据收集
       editDialogFormData:{
        orgName:"",
        name:"",
        plantUserNumber:""
       },
       // 新增对话框表格数据收集
       addDialogFormData:{
        orgName:"",
        name:"",
        plantUserNumber:""
       },
       // 编辑对话框校验规则
       editDialogFormRules:{
        orgName:[{ required: true, message: '请输入组织名称', trigger: 'blur' }],
        name:[{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
        plantUserNumber:[{ required: true, message: '请输入计划岗位人数', trigger: 'blur' }],
       },
       // 新增对话框校验规则
       addDialogFormRules:{
         name:[{ required: true, message: '请输入组织名称', trigger: 'blur' }],
         code:[{ required: true, message: '请输入组织编码', trigger: 'blur' }]
       },
       // 当前修改行的id  修改请求需要携带此id
       putId:''
    }
   },
   created() {
     // 请求树状图数据
     this.postManageTreeData()
   },
   methods: {
     // 搜索表单搜索按钮事件函数
     searchBtnClick(){
       console.log(this.searchFormData);
       // TODO 里面需要传pid和部门名称
       InstitutionManageListData().then(res => {this.tableData = res.data.data.rows;})
     },
     // 搜索表单重置按钮事件函数
     resetBtnClick(){
       // 重置表单没有作用
       this.$refs.searchFormRef.resetFields();
     },
     // 新增按钮响应函数
     addBtn(){
       this.addDialogVisible = true
     },
     // 编辑对话框取消按钮响应函数
     editDialogHandleCancel(){
       // TODO 取消按钮点击 重置对话框 表单数据
       console.log('点击取消');
       // this.$refs.editFormRef.resetFields()
       this.editDialogVisible = false
     },
     // 新增对话框取消按钮响应函数
     // TODO 新增操作结束之后需要刷新table列表
     addDialogHandleCancel(){
       // TODO 取消按钮点击 重置对话框 表单数据
       console.log('点击取消');
       // this.$refs.editFormRef.resetFields()
       this.addDialogVisible = false
     },
     // 编辑对话框确认按钮响应函数
     // TODO编辑操作结束之后需要刷新table列表
     editDialogHandleOk(){
       // TODO 收集数据 发送网络请求 成功之后 取消确认按钮加载状态 隐藏对话框
       // 校验规则没问题才发送网络请求
       console.log(111);
       postManageListDataPOST(this.putId,this.editDialogFormData).then(res => {
             // TODO 如果成功,取消加载状态,关闭对话框
             // if(res.data.status == 0){
             //   this.confirmLoading = false
             //   this.editDialogVisible = false
             // }
             console.log(res);
          }).catch(err => {
                console.log(err);
                this.editDialogVisible = false
          })
       // this.$refs.editFormRef.validate(valid => {
       //   this.confirmLoading = true
       //   console.log(valid);
       //   if(valid){
 
       //   }else{
       //     console.log('确认按钮失败');
       //   }
       // })
     },
     // 新增对话框确认按钮响应函数
     addDialogHandleOk(){
       // TODO 收集数据 发送网络请求 成功之后 取消确认按钮加载状态 隐藏对话框
       // 校验规则没问题才发送网络请求
       console.log("新增");
       this.addDialogVisible = false
     },
     //  表格删除按钮响应函数
     confirm(text){
      console.log(text);
      console.log("确认");
      if(text.actualUserNumber !== 0){
        // 实际人数大于0,不能删除
        return 
      }
      // TODO 发送网络请求,删除该项
      // 删除成功还需要再次请求列表刷新数据
      postManageListDataDelete(text.id).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      })
    },
     cancel(){
      console.log("取消");
    },
     // 表格数据编辑响应函数
     editItem(text){
       // 显示编辑对话框
       // 显示对话框的同时把数据带过去
       this.editDialogVisible = true
       this.editDialogFormData.orgName = text.orgName
       this.editDialogFormData.name = text.name
       this.editDialogFormData.plantUserNumber = text.plantUserNumber
       this.putId = text.id
       this.orgName = text.orgName
       // 目前假数据 先不带tyoe
       // this.editDialogFormData.type = text.type
       console.log('edit');
     },
     // 表格数据禁用响应函数   // Tip 暂未修改
     disabledItem(text){
       console.log(text);
       // 状态切换
       text.shield =  text.shield== 0 ? 1:0
       // 发送网络请求
       InstitutionManageListDataDisabled(text.id,text.shield).then(res => {
         console.log(res);
       })
     },
     // 点击树状图选择,并且发送网络请求,根据id查询部门分页列表
     chooseTreeNode(selectedKeys){
       // pid存起来了
       this.orgId = selectedKeys[0]
       console.log(this.orgId);
       postManageListData(this.orgId,1,10).then(res => {
         this.tableData = res.data.data.rows;console.log(this.tableData);}).catch(err => {
           console.log(err);
           this.tableData = err.data.data.rows
         })
     },
     // 左侧树状图数据请求
     postManageTreeData(){
      postManageTreeData().then(res => {
         console.log(res);
         this.realgData = res.data.data
       }).catch(err => {
        //  使用模拟数据,被拦截,暂时在.catch中完成赋值,真实数据不需要
        this.realgData = err.data.data
       })
     },
     onExpand(expandedKeys) {
       this.expandedKeys = expandedKeys;
       this.autoExpandParent = false;
     },
     onChange(e) {
       const value = e.target.value;
       const expandedKeys = dataList
         .map(item => {
           if (item.title.indexOf(value) > -1) {
             return getParentKey(item.key, gData);
           }
           return null;
         })
         .filter((item, i, self) => item && self.indexOf(item) === i);
       Object.assign(this, {
         expandedKeys,
         searchValue: value,
         autoExpandParent: true,
       });
     },
   },
   components: {
 
   }
  }
 </script>
 
 <style lang="less" scoped>
 .InstitutionManage-wrapper{
   padding: 40px 0 0 0;
 }
   .left-content{
     float: left;
     width: 20%;
     border: 1px solid #bebdbd;
     border-radius: 6px;
     // padding: 10px;
     overflow: hidden;
     h2{
       height: 49px;
       line-height: 49px;
       background-color: #F5F5F5;
       border-radius: 6px;
       font-size: 14px;
       padding: 3px 0 0 10px;
       font-weight: bold;
     }
     .leftSearchInput{
       width: 70%;
       margin-left: 30px;
       margin-top: 10px;
     }
   }
   .right-content{
     float: left;
     width: 70%;
     // border: 1px solid #999;
     padding-left: 20px;
     .search-wrapper{
       position: relative;
       width: 100%;
       height: 100px;
       border: 1px solid #bebdbd;
       border-radius: 3px;
       padding: 20px 40px;
       .serach-input{
         width: 400px;
         input{
           margin-left: 10px;
         }
       }
       .btn-group{
         position: absolute;
         right: 40px;
         top: 20px;
         button{
           margin-right: 40px;
           width: 80px;
           height: 40px;
         }
       }
     }
     .table-area{
       padding: 55px 0;
       position: relative;
       .plus-btn{
         position: absolute;
         right: 0;
         top: 10px;
         z-index: 99;
         margin-bottom: 10px;
         width: 80px;
         height: 40px;
       }
     }
   }
  
 </style>
 